#include "constants.h";

XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power"];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};
	
	_random_town = DM_Chapter_Location;
	_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
	_random_town_size = _random_town select XF_MAP_LOCATION_SIZE;
	if (_random_town_size < 200) then { _random_town_size = 200; };

	_player_detected = false;
	_thief_found = false;
	_thief_updated = false;
	_thief_dead = false;
	_documents_found = false;
	
	_enemy_initial_counts = ([DM_Chapter_Position,400,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
	_unique_id = 0;
	_reinforcements = 10;
	_detected_time = time;
	_reinforcement_trigger = _enemy_initial_counts / 4;
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_enemy_initial_counts,_reinforcement_trigger,DM_Target], Time];
	_sign = objNull;
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		_enemy_counts = ([DM_Chapter_Position,400,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
		_thief_found = ["jip_vip_found",false] call XNetGetJIP;
		_documents_found = ["jip_target_found",false] call XNetGetJIP;
		if (["jip_player_detected",false] call XNetGetJIP) then {_player_detected = true;};
		
		if (_thief_found && !_thief_updated) then {
			_spot_asl = true;
			_spot = ([DM_Chapter_Position,200,"HIDE"] call XfMissionBuildingAreaPosASL) select 0;
			_tries = 10;
			while {(_spot distance DM_Target) < 50 && _tries > 0} do {
				diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Docs too close",(_spot distance DM_Target), _spot];
				_spot = ([DM_Chapter_Position,200,"HIDE"] call XfMissionBuildingAreaPosASL) select 0;
				_tries = _tries - 1;
			};
			if (_tries <= 0) then {_spot = [];diag_log Format["(%1)[%2]: %3: %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","No buildings pos for docs",_spot];};
			if (count _spot == 0) then {
				_spot_asl = false;
				_spot = [_random_town_pos,_random_town_size] call XfGetRanPointCircle;
				_tries = 10;
				while {(_spot distance DM_Target) < 50 && _tries > 0} do {
					diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Docs too close",(_spot distance DM_Target), _spot];
					_spot = [_random_town_pos,_random_town_size] call XfGetRanPointCircle;
					_tries = _tries - 1;
				};
			};
			if (!_spot_asl) then {
				_spot set [2,((_spot select 2) + 0.5)];
				_helper = "roadcone" createVehicleLocal _spot;
				sleep 2;
				_spot = getPosASL _helper;
				deleteVehicle _helper;
				_spot_asl = true;
			};
			_obj = ["EvPhoto",_spot,"PICKUP",["STR_MF_STOLEN_DOCS","STR_MF_DOCUMENTS_FOUND","jip_target_found","STR_MF_TAKE_DOCS",True]] call XfMissionCreateMissionObject;
			_obj setPosASL _spot;
			if (requiredVersion "1.59") then {
				_sign = ["Sign_arrow_down_EP1",_spot,"REGISTER",[]] call XfMissionCreateMissionObject;
				_sign allowDamage false;
				_sign setPosASL _spot;
			};
			[false,["marker_pickup", _spot, "ICON", "ColorBlue", [0.7,0.7],"Documents",0,"hd_objective","",0.6]] call XfMissionMarker;
			["FindTheDocs","STR_MF_TASK_FINDDOCUMENTS", "STR_MF_TASK_FINDDOCUMENTS_DESK","",[],"Created"] call XfMissionTask;
			["InterrogateThief","", "","",[],"Succeeded"] call XfMissionTask;
			_thief_updated = true;
		};
	
		if (!alive DM_Target && !_thief_dead) then {
			if (!_thief_updated) then {
				["InterrogateThief","", "","",[],"Failed"] call XfMissionTask;
				_chapter_succeeded = false;
				DM_Mission_Chapter_CanRun = false;
				sleep 15;
			} else {
				"STR_MF_THIEFWONTSTEAL" call XfMissionMessageToAll;
			};
			_thief_dead = true;
		};
		
		if (_documents_found) then {
			if (!isnull _sign) then {
				deleteVehicle _sign;
			};
			["FindTheDocs","", "","",[],"Succeeded"] call XfMissionTask;
			_chapter_succeeded = true;
			DM_Mission_Chapter_CanRun = false;
			sleep 15;
		};
		
		if (DM_Mission_Chapter_CanRun AND _player_detected and !_detected_updated) then {
			_detected_updated = true;
			"STR_MF_PLAYERDETECTED" call XfMissionMessageToAll;
			_detected_time = time;
		};
		// diag_log Format["(%1)[%2]: %3: %4: en:%5  kill:%6  det:%7  flee:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Loop",_enemy_counts,_dealer_killed,_player_detected,_dealer_fleeing];
		If (DM_Mission_Chapter_CanRun AND _player_detected AND (_reinforcements != 0) AND !_tower_destroyed) then {
			// If the player is detected and no reinforcement is on the way.. Then we send new troops in :)
			if ((_enemy_initial_counts - _enemy_counts) > _reinforcement_trigger) then {
				if (_unique_id == 0) then {
					// If the reinforcement function returns a value greater than 0, it means a reinforcement was created!
					_unique_id = [d_enemy_side,[DM_Chapter_Position,200],"RANDOM",DM_Mission_RandomReinforcement] call XfMissionCallReinforcement;
					if ((_unique_id) > 0) then {
						diag_log Format["(%1)[%2]: %3: %4: reinf:%5, diff:%6, ini:%7, vec:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Sending reinforcement",_reinforcements,_enemy_diff,_enemy_initial_counts];
						_reinforcements = _reinforcements - 1;
						// hint "Reinforcement";
					};
				};
			} else {
				_unique_id = 0;
			};
		};
	};
	
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};
	
	_players_found = true;
	_enemy_count = 100;
	While {DM_Mission_Mission_CanRun && _enemy_count > 3 && _players_found} do {
		sleep 5;
		if (X_MP) then {
			_players_found = false;
			{
				if (([(getPos _x), _random_town_pos, 600] call XfPointInCircle) && isplayer _x) exitWith { _players_found = true; };
			}foreach playableUnits;
		} else {
			_players_found = ([(getPos player), _random_town_pos, 600] call XfPointInCircle);
		};
		_enemy_count = (([_random_town_pos,400,d_enemy_side] call XfMissionGetZoneSideCount) select 0);
		if (d_mission_debug_messages) then { diag_log Format["(%1)[%2]: %3: %4: player:%5  enemies:%6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Chapter End Check",_players_found,_enemy_count]; };
	};

	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_random_town","_random_town_pos","_random_town_size","_troops_power","_troops_coeff","_grpSoldiers","_grpVehicle","_i"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];

	_random_town = [true] call XfMissionGetRandomTown;
	_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
	while { (count _random_town > 0) && ((_random_town_pos distance FLAG_BASE) < 700)} do {
		_random_town = [true] call XfMissionGetRandomTown;
		_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
	};
	if ((count _random_town) <= 0) exitWith {"STR_MF_RANDOMTOWNFAILED" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	
	DM_Chapter_Location = _random_town;
	DM_Chapter_Position = _random_town_pos;
	
	_random_town_size = _random_town select XF_MAP_LOCATION_SIZE;
	if (_random_town_size < 200) then { _random_town_size = 200; };
	_random_town_name = _random_town select XF_MAP_LOCATION_DISPLAYNAME;
	diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Selected Town:",_random_town];
	
	// This indicates where the mission takes place
	[_random_town_pos,_random_town_size,_random_town_name] call XfMissionCurrentPosition;
	
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_random_town_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};

	// upsmon zone
	[true,["chapter1_random_town_zone", _random_town_pos, "ELLIPSE", "ColorRed", [_random_town_size * 1.5,_random_town_size * 1.5],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	// target zone
	[false,["chapter1_town_zone", _random_town_pos, "ELLIPSE", "ColorRed", [_random_town_size,_random_town_size],"",0,"","BDiagonal",0.5]] call XfMissionMarker;

	_spot_asl = true;
	_zone_thief = _random_town_size / 1.25;
	_spot = ([_random_town_pos,_zone_thief,"HIDE"] call XfMissionBuildingAreaPosASL) select 0;
	if (count _spot == 0) then { 
		_spot = [_random_town_pos,_zone_thief] call XfGetRanPointCircle;
		_spot_asl = false;
	};
	["jip_vip_found",false] call XNetSetJIP;
	_spot set[2, ((_spot select 2) + 0.2)];
	DM_Target = ["RU_Rocker4",d_enemy_side,_spot,"ACTIVATE",["STR_MF_M_THIEF_SPOKE","","jip_vip_found","","STR_MF_QUESTIONVIP"]] call XfMissionCreateMissionUnit;
	if (d_mission_debug_messages) then { diag_log Format["(%1)[%2]: %3: %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Placing thief",[_spot, _spot_asl]]; };
	if (_spot_asl) then {
		sleep 0.5;
		DM_Target setPosASL _spot;
	};
	DM_Target allowDamage true;
	["InterrogateThief","STR_MF_M_THIEF_TASK_INTERROGATE", "STR_MF_M_THIEF_TASK_INTERROGATE_DESC","",[],"Created"] call XfMissionTask;

	// This is HALF the zone size, we'll make an ellipse out of it so it's the ray. (thus the zone will be 2 times this value)
	_zone_thief = _random_town_size / 4.5;
	if (_zone_thief < 50) then { _zone_thief = 50; };
	_dir = [_spot, _random_town_pos] call XfDirTo;
	_dist = [(_random_town_pos select 0),(_random_town_pos select 1),0] distance [(_spot select 0),(_spot select 1),0];
	_min_dist = (_dist - _zone_thief) max 0;
	_max_dist = (_random_town_size - _zone_thief) min (_dist + _zone_thief);
	
	_dist = round(random(_max_dist - _min_dist)) + _min_dist;
	if (_dist > _random_town_size) then { _dist = _random_town_size - _zone_thief};
	_dir = _dir + (15 - random(30));
	
	_x = (_random_town_pos select 0) - (_dist * sin _dir);
	_y = (_random_town_pos select 1) - (_dist * cos _dir);
	[false,["chapter1_thief_zone", [_x,_y,0], "ELLIPSE", "ColorBlue", [(_zone_thief * 1.5),(_zone_thief * 1.2)],"",_dir,"","",0.5]] call XfMissionMarker;

	["jip_target_found",false] call XNetSetJIP;

	
	[d_enemy_side,[_random_town_pos,_random_town_size],true] call XfMissionPopulateLocation;
	// The trigger which will send reinforcement when the player is detected!
	["jip_player_detected",false] call XNetSetJIP;
	[_random_town_pos,_random_town_size * 2,d_own_side,d_enemy_side,"jip_player_detected"] call XfMissionSideDetected;
	// This will create snipers automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_Snipers] call XfMissionCreateSnipersArea;
	// This will create air support automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_AirSupport] call XfMissionCallAirSupport;
	// We will spawn civilians in a zone slightly smaller than the town.
	_amount = round(random(8)) + 5;
	[[_random_town_pos,_random_town_size * 0.8],"CIV",_amount] call XfMissionCivilianSpawn;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"STR_MF_MISSIONFAILURE1" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;